package com.sevenit.nj.yrmtfish.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sevenit.nj.yrmtfish.entity.ServerData;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ServerMaster {

	//使用本处理的父窗口.
	private Activity _activity;
	//服务器地址.
	private String _strServerIp;
	//服务器端口.
	private String _strServerPort;
	//连接字串.
	private String _strConn;
	//参数字串.
	private String _strConnPara;
	//超时设置（单位：秒）.
	private int _iTimeOut;
	//连接错误.
	private int _iConnErr;

	/**
	 * 
	 * @param a
	 */
	public ServerMaster(Activity a, String serverIp, String serverPort){
		this._activity = a;
		this._strServerIp = serverIp;
		this._strServerPort = serverPort;
		this._strConn = "";
		this._strConnPara = "";
		this._iTimeOut = 0;
		this._iConnErr = 1;
	}

	/**
	 * 设置超时时间
	 * @param iTime : 单位秒
	 * @return
	 */
	public void setTimeOut(int iTime) {
		this._iTimeOut = iTime;
	}
	
	/**
	 * 检查网络连接，如果无网络可用，就不需要进行连网操作
	 * @param activity
	 * @return
	 */
	public boolean netState() {
		Context context = this._activity.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {

				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
		
	/**
	 * 创建一个连接.
	 * @param strFunc 调用的方法名.
	 * @return
	 */
	private void connCreate(String strFunc){
		_strConn = "http://" + this._strServerIp + ":" + this._strServerPort + "/" + strFunc + ".aspx";
		_strConnPara = "";
		_iConnErr = 1;
	}
	
	/**
	 * 添加参数.
	 * @param strKey 参数名.
	 * @param strValue 调用的方法名.
	 * @return
	 */
	private void connAddPara(String strKey, String strValue){
		if(_strConnPara.length() <= 0){
			_strConnPara += "?";
		} else {
			_strConnPara += "&";
		}
		_strConnPara += strKey + "=" + java.net.URLEncoder.encode(strValue);
	}
	
	/**
	 * 提交请求.
	 * @return String 返回JSON字串.
	 */
	private String connGet(){
		
		String strResponse = "";
		
		try{
			//建立HTTP连线
			URL url=new URL(_strConn + _strConnPara);
			//打开连接，此处只是创建一个实例，并没有真正的连接
			HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
			//httpConn.connect();
			//设置连接属性
			httpConn.setDoOutput(false);//使用 URL 连接进行输出
			httpConn.setDoInput(true);//使用 URL 连接进行输入
			httpConn.setUseCaches(false);//忽略缓存
			httpConn.setRequestMethod("GET");//设置URL请求方法
			if(this._iTimeOut > 0){
				httpConn.setConnectTimeout(this._iTimeOut * 1000);
			}
			//httpConn.setRequestProperty("Content-type","application/x-www-form-urlencoded");//设置content-type
			//httpConn.setRequestProperty("Content-type","text/html; charset=GB2312");
			//获得输出流，便于向服务器发送信息.
			//DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
			//往流里面写请求参数.
			//dos.writeBytes("name="+URLEncoder.encode("chenmouren","gb2312");
			//发送完后马上关闭.
			//dos.flush();
			//dos.close();
			//获得输入流，取数据.
			InputStream input = httpConn.getInputStream();  
			InputStreamReader inputReader = new InputStreamReader(input);  
			BufferedReader reader = new BufferedReader(inputReader);  
			//BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
			//用 !=null来判断是否结束.
			//while((strLine = reader.readLine()) != null){
			strResponse = reader.readLine();
			//不能连接服务器
			if(strResponse == null || strResponse.length() <= 0){
				_iConnErr = -2;
			}
			reader.close();
			inputReader.close();
			input.close();
			httpConn.disconnect();
		} catch(SocketTimeoutException ex1){
			//连接服务器超时，请稍候再试！
			_iConnErr = -2;
		} catch(Exception ex){
			if(!netState()){
				//当前网络不可用！
				_iConnErr = -1;
			} else {
				//未知错误！
				_iConnErr = -99;
			}
		}
		
		return strResponse;
	}
	
	/**
	 * 将字符串转化为JSON对象并返回.
	 * @return
	 */
	private JSONObject getJsonObj(String strJs){
		
		try{
			return new JSONObject(strJs);
		} catch(Exception ex) {
			return null;
		}
	}
	
	/**
	 * 将字符串转化为JSON列表对象并返回.
	 * @return
	 */
	private JSONArray getJsonArray(String strJs){
		
		try{
			return new JSONArray(strJs);
		} catch(Exception ex) {
			return null;
		}
	}
	
	/**
	 * 
	 * @param jsObj
	 * @param strKey
	 * @return
	 */
	private String getJsoString(JSONObject jsObj, String strKey){
		
		try{
			if(jsObj != null && 
				strKey != null && 
				strKey.length() > 0 && 
				jsObj.has(strKey) && 
				jsObj.get(strKey) != JSONObject.NULL){
				return jsObj.getString(strKey);
			}else{
				return "";
			}
		} catch(JSONException e){
			return "";
		}
	}
    
    /**
     * 向服务器提交请求.
     * 
     * @param strFunc 服务器方法名.
     * @param mPara 参数键值对.
     * @return
     */
	public ServerData doRequest(String strFunc,Map<String,String> mPara) {
		
		//方法名.
		connCreate(strFunc);
		
		//参数.
		if(mPara != null){
			Iterator<Entry<String, String>> iter = mPara.entrySet().iterator();
			while (iter.hasNext()) {
			    Map.Entry<String,String> entry = (Map.Entry<String,String>) iter.next();
			    connAddPara(entry.getKey(),entry.getValue());
			}
		}
		
		//提交.
		String srtRes = connGet();
		JSONObject jsObj = getJsonObj(srtRes);
		JSONArray jsArray = getJsonArray(getJsoString(jsObj,"MessageContent"));
		if(jsObj != null && jsObj.has("MessageContent")){
			jsObj.remove("MessageContent");
		}
		
		//定义返回值
    	ServerData sd = new ServerData();
    	
		//设置状态.
		sd.setStatus(_iConnErr);
		//发生错误.
		if(_iConnErr <= 0){
			return sd;
		}
		
		//解析JSON串.
		try{
			int iCount = -1;
			JSONObject obj;
			while(true){
				//数据头.
				if(iCount < 0){
					if(jsObj != null && jsObj.length() > 0){
						obj = jsObj;
					}else{
						iCount++;
						continue;
					}
				} 
				//列表数据.
				else if(iCount >= 0 && jsArray != null && iCount < jsArray.length()){
					obj = (JSONObject) jsArray.get(iCount);
				} 
				//结束.
				else {
					break;
				}
				
				//创建数据.
				sd.newItem();
				Iterator<?> iter = obj.keys();
				while (iter.hasNext()) {
					String strKey = (String) iter.next();
					sd.addString(strKey, getJsoString(obj,strKey));
				}
				sd.closeItem();
				
				iCount++;
			}
		}catch(Exception e){
			sd.setStatus(-99);
		}
		
    	return sd;
	}
	
}